<template>
  <div class="contrast-page app-container details-page">
    <pubChunk>
      <span slot="title">产品对比</span>
      <div slot="headLeft" class="menu">
        <el-button type="primary" size="small" @click="drawer = true"
          ><span class="iconfont icon-chartpie"></span> 配置权重</el-button
        >
        <el-button type="primary" size="small" @click="createCombHandle"
          ><svg-icon icon-class="caidan" /> 创建组合</el-button
        >
      </div>
      <div ref="head" class="head">
        <div
          class="card flex-hc-sb"
          :class="cardBorderLine(i + 1)"
          v-for="(item, i) in strategyList"
          :key="i"
        >
          <!-- <span class="tof" v-strategy="{ id: item.strategyId, userId }">{{
            item.strategyName
          }}</span> -->
          <span class="tof"
            >【{{ typeList[item.type - 1] }}】{{ item.name }}</span
          >
          <div>
            <span class="close" @click="deleteHandle(i)">×</span>
          </div>
        </div>
        <div
          v-if="strategyList.length < 20"
          class="card flex-center pointer add"
          @click="addHandle(strategyList.length)"
        >
          <i class="iconfont icon-add-circle"></i>
          <span style="padding-left: 6px">添加对比</span>
        </div>
      </div>
    </pubChunk>

    <div class="nav flex-v-center">
      <el-form ref="dataFrom" :inline="true" label-width="82px">
        <el-form-item label="对比指标：" style="margin-bottom: 0px">
          <indexSelectTree
            :key="indexSelectTreeKey"
            :indexType.sync="index"
            size="small"
            :clearable="false"
            @contrastOptionsObj="contrastOptionsObjHandle"
          ></indexSelectTree>
        </el-form-item>
        <el-form-item style="margin: 0 0 0 20px">
          <!-- <el-button size="small" type="primary" @click="saveParamsHandle"
            >应用</el-button
          > -->
          <el-button size="small" @click="refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <pubChunk :mt="20">
      <span slot="title">收益走势图</span>
      <div slot="headLeft">
        <div class="flex wrap">
          <chart1Head
            :dateStyle="dateStyleCom()"
            ref="chart1Head"
            :more_chart1_nav_list2="more_chart1_nav_list2"
            :chartDate.sync="chart_date"
            :oldDate="oldDate"
            @sameSection="sameSectionHandle"
          ></chart1Head>
          <el-button-group style="margin-left: 14px">
            <el-button
              size="small"
              :type="dateFreq == 1 ? 'primary' : ''"
              :disabled="defaultDateFreq > 1"
              @click="dateFreq = 1"
              >日频</el-button
            >
            <el-button
              size="small"
              :type="dateFreq == 2 ? 'primary' : ''"
              :disabled="defaultDateFreq > 2"
              @click="dateFreq = 2"
              >周频</el-button
            >
            <el-button
              size="small"
              :type="dateFreq == 3 ? 'primary' : ''"
              @click="dateFreq = 3"
              >月频</el-button
            >
          </el-button-group>
          <el-checkbox
            v-if="strategyList.length > 1"
            style="margin-left: 14px"
            class="flex-v-center"
            v-model="showBeyondIncome"
            >显示超额曲线</el-checkbox
          >
        </div>
      </div>
      <!-- v-if="hasNetworth && Object.keys(contrastOptions_obj).length" -->
      <div v-show="showChunk1">
        <Chart1
          v-if="Object.keys(contrastOptions_obj).length"
          :contrastOptions_obj="contrastOptions_obj"
          id="contrastChart1"
          :userId="userId"
          :ids="uuid"
          :contrastList="strategyList"
          :id_index.sync="index"
          :chart_date="chart_date"
          :showBeyondIncome="showBeyondIncome"
          name1="模拟组合"
          name2="模拟组合"
          :indexNames="beyondIncome_selList"
          typePage="contrast"
          :sameSection="sameSection"
          @loadingOk="loadingOkHandle"
          @viewObj="viewObjHandle"
          :dateFreq.sync="dateFreq"
          :defaultDateFreq.sync="defaultDateFreq"
          :height="280"
          width="100%"
        />
        <!-- <div v-else style="height: 460px"></div> -->
      </div>
    </pubChunk>

    <pubChunk :mt="20">
      <span slot="title">收益风险指标</span>
      <div v-show="showChunk2" :key="list_riskIndicators_key" class="showChunk">
        <el-table
          v-loading="listLoading_riskIndicators && strategyList.length"
          :data="list_riskIndicators"
          stripe
          fit
          size="mini"
          style="width: 100%"
          :cell-class-name="cellClass"
          :cell-style="{ padding: '8px 0' }"
          :header-cell-style="{  color: '#333' }"
        >
          <el-table-column prop="name" label="名称" fixed="left" :width="flexColumnWidth('名称', 'name', list_riskIndicators)">
            <template slot-scope="{ row }">
              <span :title="row.name">
              <router-link
                v-if="row.type == 1"
                style="cursor: pointer; color: #1890ff"
                :to="{
                  path: '/policyManage/netWorthAnalysis/' + row.id,
                  query: { userId }
                }"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <router-link
                v-else-if="row.type == 2"
                style="cursor: pointer; color: #1890ff"
                :to="'/strategyComb/groupManage/netWorthAnalysis/' + row.id"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <router-link
                v-else-if="row.type == 3"
                style="cursor: pointer; color: #1890ff"
                :to="'/strategyComb/combManage/netWorthAnalysis/' + row.id"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <router-link
                v-else-if="row.type == 4"
                style="cursor: pointer; color: #1890ff"
                :to="'/afterManage/investList/details/' + row.id"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <router-link
                v-else-if="row.type == 5"
                style="cursor: pointer; color: #1890ff"
                :to="'/afterManage/subInvest/details/' + row.id"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <router-link
                v-else-if="row.type == 6"
                style="cursor: pointer; color: #1890ff"
                :to="'/afterManage/combination/details/' + row.id"
              >
                <span>[{{ typeList[row.type - 1] }}]</span>{{ row.name }}
              </router-link>
              <span v-else
                ><span v-show="row.type">[{{ typeList[row.type - 1] }}]</span
                >{{ row.name }}</span
              >
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="权重" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.weight"
                >{{ scope.row.weight | toFixed2 }}%</span
              >
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="incomeRate"
            label="收益率"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span
                v-if="row.incomeRate"
                :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
              >
                {{ row.incomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualizedIncomeRate"
            label="年化收益"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row && scope.row.annualizedIncomeRate"
                :class="
                  scope.row.annualizedIncomeRate >= 0
                    ? 'positiveFc'
                    : 'negativeFc'
                "
              >
                {{ scope.row.annualizedIncomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualFluctuationsRate"
            label="年化波动"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.annualFluctuationsRate != null">{{
                row.annualFluctuationsRate
              }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="sharpeRate" label="夏普比率" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.sharpeRate != null">{{ row.sharpeRate }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maximumDrawdownRate"
            label="最大回撤"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maximumDrawdownRate != null">{{
                row.maximumDrawdownRate
              }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="calmarRate" label="卡玛比率" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.calmarRate != null">{{ row.calmarRate }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxBackIncomDay"
            label="最大回撤回补期"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxBackIncomDay && row.maxBackIncomDay > 0">{{
                row.maxBackIncomDay
              }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxNotByNewHightDay"
            label="最大不创新高天数"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxNotByNewHightDay">{{
                row.maxNotByNewHightDay
              }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="investWinningRate"
            label="投资胜率"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.investWinningRate != null">{{
                row.investWinningRate
              }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </pubChunk>

    <pubChunk :mt="20">
      <span slot="title" class="line">
        <span
          slot="title"
          class="showMonth_navList-item"
          :class="{
            'showMonth_navList-item_active': showMonth_navList_active == i
          }"
          v-for="(item, i) in showMonth_navList"
          :key="i"
          @click="showMonthNavHandle(i)"
        >
          {{ item }}
        </span>
      </span>
      <div slot="headLeft" class="cutTableChart_icon">
        <div class="line">
          <div class="showMonth">
            <div class="round round1"></div>
            模拟组合
          </div>
          <div class="showMonth">
            <div class="round round2"></div>
            <el-select
              style="width: 130px"
              v-model="month_contrast"
              size="mini"
              clearable
              placeholder="请选择"
              @change="monthContrastHandle"
            >
              <el-option
                v-for="item in one_contrastOptions_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div style="margin-left: 26px">
          <svg-icon
            icon-class="zhuzhuangtu"
            :class="{
              showMonth_cutIcon_active: showMonth_cutIcon_active == 1
            }"
            @mouseenter="showMonthCutIcon(1)"
          />
          <svg-icon
            icon-class="caidan"
            :class="{
              showMonth_cutIcon_active: showMonth_cutIcon_active == 2
            }"
            @mouseenter="showMonthCutIcon(2)"
          />
        </div>
      </div>
      <div v-show="showChunk4" class="showChunk">
        <!-- 月度收益 -->
        <el-table
            v-show="
              showMonth_navList_active == 3 && showMonth_cutIcon_active == 2
            "
            fit
            :data="list_showMonth"
            style="width: 100%;"
            row-key="rowKey"
            size="mini"
            max-height="516"
            lazy
            :load="loadChildTable"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :cell-style="{ padding: '8px 0' }"
            :header-cell-style="{ color: '#333' }"
            :cell-class-name="showMonthTableClassName"
          >
            <el-table-column prop="year" label="年份" fixed="left" :width="flexColumnWidth('名称', 'name', list_riskIndicators)">
              <template slot-scope="{ row }">
                <div style="cursor: default;">{{ row.year }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="名称"
              width="150"
              prop="name"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop=""
              :label="`${i}月`"
              align="center"
              v-for="i in 12"
              :key="i"
            >
              <template slot-scope="{ row }">
                <span
                  v-if="row[i + '_growthRate'] != null"
                  :class="
                    row[i + '_growthRate'] >= 0 ? 'positiveFc' : 'negativeFc'
                  "
                >
                  {{ row[i + '_growthRate'] }}%
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="YTD" align="center">
              <template slot-scope="{ row }">
                <span
                  v-if="row['13_growthRate'] != null"
                  :class="row['13_growthRate'] >= 0 ? 'positiveFc' : 'negativeFc'"
                >
                  {{ row['13_growthRate'] }}%
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
        </el-table>
        <!-- 季度收益 -->
        <div
            v-show="
              showMonth_navList_active == 2 && showMonth_cutIcon_active == 2
            "
            v-loading="listLoading_showMonth_table1"
            style="min-height: 200px;"
          >
            <el-table
              class="pub_tableTree_maxBack"
              v-if="showMonth_table1.length"
              :data="showMonth_table1"
              fit
              row-key="rowKey"
              size="mini"
              max-height="516"
              :cell-class-name="cellClass"
              :cell-style="{ padding: '8px 0' }"
              :tree-props="{ children: 'children' }"
              :header-cell-style="{ color: '#333' }"
              style="width: 100%;"
            >
              <el-table-column
                prop="definition"
                label="名称/季度"
                align="left"
                fixed="left"
                :width="flexColumnWidth('名称/季度', 'definition', showMonth_table1)"
              >
                <template slot-scope="scope"><span :title="scope.row.definition">{{ scope.row.definition }}</span></template>
              </el-table-column>
              <el-table-column
                prop=""
                :label="item.quarterName"
                align="center"
                min-width="160"
                v-for="(item, i) in showMonth_table1[0].list"
                :key="i"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.list[i] &&
                      scope.row.list[i].sumPnl != null &&
                      scope.row.quarterName == '· 最大回撤'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span
                    v-else-if="
                      scope.row.list[i] && scope.row.list[i].sumPnl != null
                    "
                    :class="
                      scope.row.list[i].sumPnl >= 0 ? 'positiveFc' : 'negativeFc'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
            </el-table>
        </div>
        <!-- 年度收益 -->
        <div
            v-show="
              showMonth_navList_active == 1 && showMonth_cutIcon_active == 2
            "
            v-loading="listLoading_showMonth_table2"
            style="min-height: 200px;"
          >
            <el-table
              class="pub_tableTree_maxBack"
              v-if="showMonth_table2.length"
              :data="showMonth_table2"
              fit
              row-key="rowKey"
              size="mini"
              max-height="516"
              :cell-class-name="cellClass"
              :cell-style="{ padding: '8px 0' }"
              :tree-props="{ children: 'children' }"
              :header-cell-style="{ color: '#333' }"
              style="width: 100%;"
            >
              <el-table-column
                prop="definition"
                label="年份/名称"
                align="left"
                fixed="left"
                :width="flexColumnWidth('年份/名称', 'definition', showMonth_table2)"
              >
                <template slot-scope="scope"><span :title="scope.row.definition">{{ scope.row.definition }}</span></template>
              </el-table-column>
              <el-table-column
                prop=""
                :label="item.quarterName"
                align="center"
                min-width="160"
                v-for="(item, i) in showMonth_table2[0].list"
                :key="i"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.list[i] &&
                      scope.row.list[i].sumPnl != null &&
                      scope.row.quarterName == '· 最大回撤'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span
                    v-else-if="
                      scope.row.list[i] && scope.row.list[i].sumPnl != null
                    "
                    :class="
                      scope.row.list[i].sumPnl >= 0 ? 'positiveFc' : 'negativeFc'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
            </el-table>
        </div>
        <!-- 区间收益-表格 -->
        <div
            v-show="
              showMonth_navList_active == 0 && showMonth_cutIcon_active == 2
            "
            v-loading="listLoading_showMonth_table3"
            style="min-height: 200px;"
          >
            <el-table
              class="pub_tableTree_maxBack"
              v-if="showMonth_table3.length"
              :data="showMonth_table3"
              fit
              row-key="rowKey"
              size="mini"
              max-height="516"
              :cell-class-name="cellClass"
              :cell-style="{ padding: '8px 0' }"
              :tree-props="{ children: 'children' }"
              :header-cell-style="{ color: '#333' }"
              style="width: 100%;"
            >
              <el-table-column
                prop="definition"
                label="名称/年份"
                align="left"
                fixed="left"
                :width="flexColumnWidth('名称/年份', 'definition', showMonth_table3)"
              >
                <template slot-scope="scope"><span :title="scope.row.definition">{{ scope.row.definition }}</span></template>
              </el-table-column>
              <el-table-column
                prop=""
                :label="item.quarterName"
                align="center"
                min-width="80"
                v-for="(item, i) in showMonth_table3[0].list"
                :key="i"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.list[i] &&
                      scope.row.list[i].sumPnl != null &&
                      scope.row.quarterName == '· 最大回撤'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span
                    v-else-if="
                      scope.row.list[i] && scope.row.list[i].sumPnl != null
                    "
                    :class="
                      scope.row.list[i].sumPnl >= 0 ? 'positiveFc' : 'negativeFc'
                    "
                  >
                    {{ scope.row.list[i].sumPnl | toFixed2 }}%
                  </span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
            </el-table>
        </div>
        <div class="month-chartContent">
          <div v-if="showMonth_cutIcon_active == 1" class="mChunk1">
            <month-return-chart
              v-loading="list_monthNetWorthDistributed_loading"
              id="groupManageMonthReturnChart"
              :name_contrast="name_contrast"
              :chart_date="chart_date"
              :month_contrast="month_contrast"
              y-name="模拟组合"
              :data="list_monthNetWorthDistributed"
              :showMonth_navList_active="showMonth_navList_active"
              :height="400"
              width="100%"
            />
          </div>
        </div>
      </div>
    </pubChunk>

    <pubChunk :mt="20">
      <span slot="title">产品相关性</span>
      <div slot="headLeft" class="relevance-tip">
        <div class="red-block"></div>
        高相关性≥0.8 (占比{{ highRelevanceRate || 0 }})
        <div class="yellow-block"></div>
        0≤低相关性≤0.3 (占比{{ lowRelevanceRate || 0 }})
        <div class="green-block"></div>
        负相关性&lt;0 (占比{{ negativeRelevanceRate || 0 }})
      </div>
      <div v-show="showChunk3" class="showChunk">
        <el-table
          v-loading="listLoading_productRelevance"
          :data="relevance_list"
          border
          stripe
          fit
          size="mini"
          style="width: 100%"
          :cell-style="{ padding: '0',height:'40px'  }"
          :header-cell-style="{ padding: '0', color: '#333',height:'40px', }"
          :cell-class-name="relevanceTableRowClassName"
        >
          <el-table-column
            type="index"
            width="200"
            label="产品名称"
            :index="relevanceTitleHandle"
          >
            <template  slot-scope="scope">
              <div class="productName" style="line-height:15px;" :title="scope.row.strategyName">
                {{scope.row.strategyName}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="`list[${i}].productRelevance`"
            :label="item.strategyName"
            v-for="(item, i) in relevance_list"
            :key="i"
            align="center"
            min-width="120"
          >
              <template slot="header">
                <div :title="item.strategyName" class="productName" style="line-height:15px;font-size:12px;min-width:100px">
                  {{item.strategyName}}
                </div>
              </template>
          </el-table-column>
        </el-table>
      </div>
    </pubChunk>

    <div style="height: 150px"></div>

    <allStrategyOpen
      v-if="addOrUpdateVisible"
      title="添加对比产品（多选）"
      type="check"
      ref="addOrUpdate"
      :userId="userId"
      :bulletinBoardList="strategyList"
      :surplusNum="20 - strategyList.length"
      @selctInvestName="selctInvestNameHandle"
      @selCheckctInvestName="selCheckctInvestNameHandle"
    ></allStrategyOpen>

    <el-drawer size="680px" :with-header="false" :visible.sync="drawer">
      <pubChunk>
        <div slot="title">已选列表（{{ strategyList.length }}）</div>
        <i
          slot="headLeft"
          class="pointer el-icon-close"
          @click="drawer = false"
        ></i>
        <div class="drawerContent">
          <el-table
            ref="table"
            :data="strategyList"
            fit
            size="mini"
            :header-cell-style="{ background: '#F5F7FA', color: '#32639d' }"
          >
            <el-table-column prop="name" label="产品名称" min-width="100">
              <template slot-scope="{ row }">
                <span>【{{ typeList[row.type - 1] }}】{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="leverageRatio"
              label="杠杆率"
              min-width="64"
              show-overflow-tooltip
            >
              <template slot-scope="{ row }">
                <el-input
                  size="mini"
                  v-model="row.leverageRatio"
                  style="width: 64px"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="weight"
              label="权重(%)"
              min-width="100"
              show-overflow-tooltip
            >
              <template slot-scope="{ row }">
                <el-input
                  size="mini"
                  v-model="row.weight"
                  style="width: 100px"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="" label="" width="60" align="center">
              <template slot-scope="{ $index }">
                <i
                  class="el-icon-close pointer"
                  @click="deleteHandle($index, 'drawer')"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer">
          <div class="pubChunk_footer flex-hc-sb">
            <p>
              可配置权重：<span
                :class="surplusWeight < 0 ? 'positiveFc' : 'negativeFc'"
                >{{ surplusWeight }}%</span
              >
            </p>
            <div>

              <el-button-group>
                <el-button :class="{drawerBtn_active: drawerBtnActive==1}" size="small" @click="riskParityPortfolioHandle(1)"
                  >风险平价</el-button
                >
                <el-button :class="{drawerBtn_active: drawerBtnActive==2}" size="small" @click="meanCovPortfolioHandle(2)"
                  >均值方差</el-button
                >
              </el-button-group>
              <el-button :class="{drawerBtn_active: drawerBtnActive==3}" size="small" style="margin-left: 10px;" @click="equalWeightHandle(3)"
                >等权</el-button
              >
              <el-button size="small" type="primary" @click="weightSubmit"
                >保存</el-button
              >
            </div>
          </div>
        </div>
      </pubChunk>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { findClassifyNetWorthExtendBySegment } from "@/api/groupManage";
import {
  getMonthlyIndex,
  getIndexRiskByIndexTypeAndTime,
  findTimeScopeGrowth
} from "@/api/policyManage";
import { riskParityPortfolio, meanCovPortfolio } from "@/api/combination";
import {
  compareStrategyNew,
  getCompareStrategyInfo,
  findCompareNetWorthExtendBySegment,
  findSegmentCompareNetWorthDistribute,
  getCompareMonthly,
  getCompareMonthlyDsitribute,
  getCompareYear,
  getCompareYearDistribute,
  getCompareQuarter,
  getCompareQuarterDistribute,
  getProductRelevanceNew,
  compareMonthlyIncreaseDialog
} from "@/api/contrast";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import monthReturnChart from "@/components/Charts/barEcharts_monthReturn.vue";
import Chart1 from "@/components/Charts/strategyComb/groupManage/chart1.vue";
import allStrategyOpen from "@/views/other/allStrategyOpen.vue";
import chart1Head from "@/components/investComn/chart1Head.vue";
import { deepClone, downFixed } from "@/utils";
import { riskIndexCalc } from "@/utils/pro";
import pubChunk from "@/components/investComn/pubChunk.vue";
import { format } from "date-fns";
import {  } from '@/api/contrast'
import { getMaxLength } from "@/utils/pro";


export default {
  name: "Contrast",
  components: {
    Chart1,
    indexSelectTree,
    // showMonthOpen,
    monthReturnChart,
    chart1Head,
    pubChunk,
    allStrategyOpen
  },
  data() {
    return {
      drawerBtnActive: null,
      typeList: ['策略', '分类', '组合', '投资', '子投资', '投资组合', '指数'],
      typeIds: ["C", "F", "Z", "AT", "AZT", "AZ", 'ZZ'],
      // typeList: ['策略', '分类', '组合', '投资', '子投资', '投资组合'],
      // typeIds: ["C", "F", "Z", "AT", "AZT", "AZ"],

      drawer: false,
      beyondIncome_selList: [],
      showBeyondIncome: false, // 超额收益

      loading: false,

      defaultDateFreq: undefined,
      dateFreq: undefined,

      uuid: null,
      strategyList: [],
      contrastOptions_obj: {},

      hasNetworth: false,

      index: [],
      indexSelectTreeKey: 1,
      chart_date: [],
      oldDate: [],
      more_chart1_nav_list2: [],
      sameSection: false,

      showChunk1: true,
      showChart1: false,
      data_chart1: [],

      showChunk2: true,
      listLoading_riskIndicators1: true,
      listLoading_riskIndicators2: true,
      list_riskIndicators_key: 1,
      list_riskIndicators: [],
      _list_riskIndicators: [], // 保存基础 收益风险指标
      add_column_list: [],
      riskIndicators_columnLabel: {
        annualizedIncomeRate: "年化收益",
        annualFluctuationsRate: "年化波动",
        sharpeRate: "夏普比率",
        maximumDrawdownRate: "最大回撤回补期",
        calmarRate: "卡玛比率",
        maxBackIncomDay: "最大回补天数",
        investWinningRate: "投资胜率"
      },

      showChunk3: true,
      listLoading_productRelevance: false,
      relevance_list: [],

      showChunk4: true,
      showMonth_navList: ["区间收益", "年度收益", "季度收益", "月度收益"],
      combTreeValue: "",
      showMonth_navList_active: 0,
      showMonth_cutIcon_active: 2,
      // 季度收益
      listLoading_showMonth_table1: false,
      listLoading_showMonth_table2: false,
      listLoading_showMonth_table3: false,
      list_monthNetWorthDistributed_loading: false,
      showMonth_table1: [],
      showMonth_table2: [],
      showMonth_table3: [],
      one_contrastOptions_list: [],
      month_contrast: undefined,
      name_contrast: "",
      list_showMonth: [],
      _list_showMonth: [],

      monthChartBtn: 0,
      list_showMonth_profit: [],
      list_showMonth_key: 0,
      list_showMonth_profit_column1: [
        { id: 99, name: "成立以来" },
        { id: 0, name: "今年以来" },
        { id: 1, name: "近1月" },
        { id: 3, name: "近3月" },
        { id: 6, name: "近6月" },
        { id: 12, name: "近1年" },
        { id: 24, name: "近2年" },
        { id: 36, name: "近3年" }
      ],
      list_monthNetWorthLine: [], // 收益分布
      findNetWorthExtendByStrategyId2_loading: false, // 收益分布 列表loading
      list_monthNetWorthDistributed: [], // 月度回报 echart
      list_table_getMonthNetWorthDetial: [], // 月度回报 列表
      getMonthNetWorthDetial_loading: false, // 月度回报 列表loading
      monthNetWorthDetial_listQuery: {
        // 月度回报 分页
        pageCurrent: 1,
        limit: 10
      },
      monthNetWorthDetial_total: 0,

      addOrUpdateVisible: false,

      chart1List: [],
      highRelevanceRate: '',
      lowRelevanceRate: '',
      negativeRelevanceRate: '',
      // localStorage存储的key
      ss_key: "",
      maxNameWidth: 100
    };
  },
  computed: {
    ...mapGetters(["userId", "createCombId", "createComb"]),
    cardBorderLine() {
      return (i) => {
        const length = this.strategyList.length + 1;
        let base = Math.floor(length / 5);
        if (length % 5 == 0) base--;
        if (i / 5 <= base) {
          return "cardBorder";
        }
      };
    },
    surplusWeight() {
      let res = 100;
      this.strategyList.forEach((item) => {
        res = (res - item.weight).toFixed(6)
      });
      res = downFixed(res, 2);
      // return res>0 ? res : 0
      return res;
    },
    listLoading_riskIndicators() {
      if (
        !this.listLoading_riskIndicators1 &&
        !this.listLoading_riskIndicators2
      ) {
        return false;
      }
      return true;
    },
    strategyList0Name() {
      return this.strategyList[0]
        ? JSON.parse(JSON.stringify(this.strategyList[0].name))
        : "";
    }
  },
  watch: {
    index(newVal, oldVal) {
      if (newVal.length > 4) {
        this.$message({
          message: "最多选择4个对比指标",
          type: "warning",
          duration: 2000
        });
        this.$nextTick(() => {
          this.index = oldVal;
        });
      } else if (Object.keys(this.contrastOptions_obj).length) {
        this.one_contrastOptions_list = [];
        this.beyondIncome_selList = JSON.parse(
          JSON.stringify(this.strategyList)
        );
        newVal.forEach((item) => {
          this.one_contrastOptions_list.push({
            id: item,
            name: this.contrastOptions_obj[item]
          });
          this.beyondIncome_selList.push({
            type: 7, //指数
            id: item,
            // gId: this.typeIds[6] + item,
            gId: item,
            name: this.contrastOptions_obj[item]
          });
        });
        this.getIndexRiskByIndexTypeAndTime(
          this.chart_date[0],
          this.chart_date[1]
        );
      }
      this.indexSelectTreeKey++
    },
    month_contrast(val) {
      if (val) {
        this.name_contrast = this.contrastOptions_obj[val]; // 月度表现头部修改
      }
      this.showMonthNavHandle(this.showMonth_navList_active);
    },
    listLoading_riskIndicators(val) {
      if (!val) {
        this.$nextTick(() => {
          this.list_riskIndicators = this.riskRecursionHandle(
            this.chart1List,
            this.list_riskIndicators
          );
          this.list_riskIndicators_key++;
        });
      }
    },
    strategyList0Name: {
      handler(val) {
        // 多开标签 设置
        this.tempRoute = Object.assign({}, this.$route);
        this.$setTagsViewTitle(this.tempRoute, `产品对比-${val}`);
        document.title = `产品对比-${val}`;
      }
    }
  },
  created() {
    const one = this.$route.query.one;
    if (one != 0) {
      let list = [];
      this.ss_key = this.$route.path.split("/").slice(-1)[0];
      const data = localStorage.getItem(this.ss_key);
      if (data) {
        list = JSON.parse(data);
      } else {
        list = JSON.parse(this.$route.query.list);
      }
      if (list.length) this.init(list);
    }
  },
  updated() {
    for (let index = 0; index < document.getElementsByClassName('productName').length; index++) {
      const element = document.getElementsByClassName('productName')[index];
      element.className = 'productName'
      if(element.offsetHeight > 40) {
        element.className = 'productName mlOverflow'
      }else{
        element.className = 'productName'
      }
    }
  },
  destroyed() {
    localStorage.removeItem(this.ss_key);
  },
  methods: {
    init(list) {
      list.map((item) => {
        this.strategyList.push({
          ...item,
          gId: this.typeIds[item.type - 1] + item.id,
          leverageRatio: 1,
          weight: ((1 / list.length) * 100).toFixed(2)
        });
      });
      this.beyondIncome_selList = this.strategyList;
      this.weightSubmit();
    },
    dateStyleCom() {
      const el = document.getElementsByClassName('head')[0]
      if(el) {
        const height = el.offsetHeight
        const res = 'top: ' + (height + 366) + 'px;'
        return res
      }
    },
    createCombHandle() {
      const list = this.strategyList.filter((item) => item.type == 1 || item.type == 4 || item.type == 5);
      if (list.length < 2) {
        this.$message({
          message: "请至少选择2条以上[策略]、[投资]、[子投资]产品",
          type: "warning"
        });
        return;
      }
      const strategyClassifyVo = [
        {
          classfyName: "默认分类",
          classifyId: null,
          classifyNetWorth: null,
          classifyNetWorthBean: null,
          classifyNetWorthExtendBeans: null,
          classifyNetWorthTime: null,
          classifyStrategyExt: [],
          compositionId: null,
          compositionName: null,
          compositionWeight: 100,
          createdBy: 1,
          createdName: null,
          createdTime: format(new Date(), "YYYY-MM-DD"),
          defaultStatus: 1,
          hasNetWorth: null,
          incomRateYear: null,
          indexType: null,
          initMoney: null,
          initialMoney: null,
          investMoney: null,
          mark: null,
          nominalAmount: null,
          riskIndicatorsBean: null,
          updatedBy: null,
          updatedTime: null,
          uuid: null,
          volityRateYear: null,
          weight: null
        }
      ];
      list.forEach((item) => {
        strategyClassifyVo[0].classifyStrategyExt.push({
          classifyId: null,
          currentMoney: null,
          enterTime: item.enterTime,
          initialMoney: null,
          leverageRatio: 1,
          minWarehouseAdjustmentCycleEquity: 0,
          nominalAmount: null,
          strategyAccumulationType: 1,
          strategyId: item.id,
          strategyName: item.name,
          uuid: null,
          weight: null,
          yearIncom: null,
          yearMaxdown: null
        });
      });
      const obj = {
        strategyClassifyVo,
        strategyCompositionVo: {
          compositionId: null,
          compositionName: "",
          compositionNetWorth: null,
          compositionNetWorthExtendBeans: null,
          compositionWeight: null,
          createdBy: this.userId,
          createdName: null,
          createdTime: format(new Date(), "YYYY-MM-DD"),
          fixedIncome: 0,
          hasClassify: false,
          hasNetWorth: null,
          indexType: null,
          initMoney: null,
          mark: ""
        }
      };
      this.$store.commit("contrast/addCreateComb", obj);
      this.$router.push({
        path: "/strategyComb/combManage/config",
        query: {
          compositionId: this.createCombId,
          type: "created"
        }
      });
    },
    riskParityPortfolioHandle(i) {
      this.drawerBtnActive = i
      const tag = this.strategyList.find(item => item.leverageRatio=='')
      if(tag) {
        this.$message('杠杆率不能有空')
        return
      }
      const params = this.strategyList.map(item => {
        return {
          childrenId: item.id,
          childrenName: item.name,
          childrenStatus: item.type,
          annualizedIncome: item.annualizedIncome,
          annualFluctuations: item.annualFluctuations,
          frequency: 1,
          percentageDown: 0,
          percentageUp: 100
        }
      })
      riskParityPortfolio(params).then(res => {
        let num_weight = 0
        for (const key in res.body.maps) {
          const item = res.body.maps[key]
          const i = this.strategyList.findIndex(item => item.name==key)
          if(i!=-1) {
            this.strategyList[i].name_weight = item
            num_weight += (item / this.strategyList[i].leverageRatio)
          }
        }
        this.strategyList.forEach(item => {
          item.weight = (item.name_weight / item.leverageRatio / num_weight * 100).toFixed(2)
        })
      })
    },
    meanCovPortfolioHandle(i) {
      this.drawerBtnActive = i
      const tag = this.strategyList.find(item => item.leverageRatio=='')
      if(tag) {
        this.$message('杠杆率不能有空')
        return
      }
      const params = this.strategyList.map(item => {
        return {
          childrenId: item.id,
          childrenName: item.name,
          childrenStatus: item.type,
          annualizedIncome: item.annualizedIncome,
          annualFluctuations: item.annualFluctuations,
          frequency: 1,
          percentageDown: 0,
          percentageUp: 100
        }
      })
      meanCovPortfolio(params).then(res => {
        let num_weight = 0
        for (const key in res.body.maps) {
          const item = res.body.maps[key]
          const i = this.strategyList.findIndex(item => item.name==key)
          if(i!=-1) {
            this.strategyList[i].name_weight = item
            num_weight += (item / this.strategyList[i].leverageRatio)
          }
        }
        this.strategyList.forEach(item => {
          item.weight = (item.name_weight / item.leverageRatio / num_weight * 100).toFixed(2)
        })
      })
    },
    equalWeightHandle(i) {
      this.drawerBtnActive = i
      this.strategyList.map((item) => {
        item.weight = ((1 / this.strategyList.length) * 100).toFixed(2);
      });
    },
    viewObjHandle(data) {
      this.chart1List = riskIndexCalc(data);
      this.list_riskIndicators = this.riskRecursionHandle(
        this.chart1List,
        this.list_riskIndicators
      );
      this.list_riskIndicators_key++;
    },
    riskRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name);
        if (resList_i != -1) {
          const res = resList[resList_i];
          list[i] = {
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            type: items.type,
            id: items.id,
            ...res
          };
        } else if (items.children) {
          // 分类
          items.children.forEach((_) => {
            list[i] = {
              annualFluctuationsRate: "--",
              sharpeRate: "--",
              maxBackIncomDay: "--",
              maximumDrawdownRate: "--",
              calmarRate: "--",
              investWinningRate: "--",
              ...list[i]
            };
          });
        }
        if (items.children) this.riskRecursionHandle(resList, items.children);
      });
      // list[0].nominalAmount = this.nominalAmount
      return list;
    },
    showMonthCutIcon(i) {
      this.showMonth_cutIcon_active = i;
    },
    // 切换月度表现nav
    showMonthNavHandle(i) {
      this.showMonth_navList_active = i;
      switch (i) {
        case 0:
          if (
            !this.showMonth_table3.length ||
            this.old_month_contrast3 != this.month_contrast
          ) {
            this.old_month_contrast3 = this.month_contrast;
            this.getClassifySegment();
          }
          this.getSegmentClassifyNetWorthDistribute();
          break;
        case 1:
          if (
            !this.showMonth_table2.length ||
            this.old_month_contrast2 != this.month_contrast
          ) {
            this.old_month_contrast2 = this.month_contrast;
            this.getClassifyYear();
          }
          this.getCompareYearDistribute();
          break;
        case 2:
          if (
            !this.showMonth_table1.length ||
            this.old_month_contrast1 != this.month_contrast
          ) {
            this.old_month_contrast1 = this.month_contrast;
            this.getClassifyQuarter();
          }
          this.getQuarterClassifyNetWorthDistribute();
          break;
        case 3:
          this.getMonthNetWorthDistributed(this.uuid);
          break;
        default:
          break;
      }
    },
    getClassifyQuarter() {
      this.listLoading_showMonth_table1 = true;
      getCompareQuarter({
        uuid: this.uuid,
        indexTypes: this.month_contrast ? [this.month_contrast] : null,
        indexNames: this.name_contrast ? [this.name_contrast] : null
      }).then((res) => {
        this.listLoading_showMonth_table1 = false;
        console.log("季度收益", res);
        this.showMonth_table1 = this.segmentMaxBackHandle(res.body);
      });
    },
    getClassifyYear() {
      this.listLoading_showMonth_table2 = true;
      getCompareYear({
        uuid: this.uuid,
        indexTypes: this.month_contrast ? [this.month_contrast] : null,
        indexNames: this.name_contrast ? [this.name_contrast] : null
      }).then((res) => {
        this.listLoading_showMonth_table2 = false;
        console.log("年度收益", res);
        this.showMonth_table2 = this.segmentMaxBackHandle(res.body);
      });
    },
    getClassifySegment() {
      this.listLoading_showMonth_table3 = true;
      findCompareNetWorthExtendBySegment({
        uuid: this.uuid,
        indexTypes: this.month_contrast ? [this.month_contrast] : null,
        indexNames: this.name_contrast ? [this.name_contrast] : null,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1]
      }).then((res) => {
        this.listLoading_showMonth_table3 = false;
        console.log("区间收益", res);
        this.showMonth_table3 = this.segmentMaxBackHandle(res.body);
      });
    },
    sameSectionHandle(val) {
      this.sameSection = val;
    },
    loadingOkHandle() {
      this.loading = false;
    },
    weightSubmit() {
      this.loading = true;
      let num = 0;
      this.strategyList.map((item) => {
        num += Number(item.weight);
      });
      if (num < 99 || 101 < num) {
        this.$message({
          type: "warning",
          message: "总权重相加之和不等于100"
        });
        this.loading = false;
        return;
      }
      this.drawer = false;
      this.hasNetworth = false;
      const paramsList = this.strategyList.map((item) => {
        return {
          childrenId: item.id,
          childrenName: item.name,
          childrenStatus: item.type,
          leverageRatio: item.leverageRatio,
          weight: item.weight
        };
      });
      localStorage.setItem(this.ss_key, JSON.stringify(this.strategyList)); // 存储当前选择的策略，避免刷新时清除掉
      compareStrategyNew({
        strategyCompares: paramsList
      }).then((res) => {
        this.hasNetworth = true;
        this.uuid = res.body.uuid;
        const dates = [];
        dates[0] = res.body.startTime;
        dates[1] = res.body.endTime;
        if (this.$refs.chart1Head.cns_active == 0) this.chart_date = dates;
        this.oldDate = deepClone(dates);
        let year0 = Number(this.chart_date[0].slice(0, 4));
        const year1 = Number(this.chart_date[1].slice(0, 4));
        this.more_chart1_nav_list2 = [];
        while (year0 <= year1) {
          this.more_chart1_nav_list2.push(year0 + "年度");
          year0++;
        }

        this.getriskIndicators(dates[0], dates[1]);
        // this.findNetWorthExtendByStrategyId2();

        this.getProductRelevance();
        this.getMonthNetWorth();
        // this.getMonthNetWorthDistributed();

        this.getClassifySegment();
        this.getSegmentClassifyNetWorthDistribute();
        this.getClassifyYear();
        this.getClassifyQuarter();
      });
    },
    contrastOptionsObjHandle(obj) {
      this.contrastOptions_obj = obj;
    },
    deleteHandle(i, type) {
      if (this.strategyList.length <= 2) {
        this.$message({
          type: "warning",
          message: "至少保留2条以上策略",
          duration: 2000
        });
        return false;
      }
      this.strategyList.splice(i, 1);
      this.one_contrastOptions_list.splice(i, 1);
      if (!type) {
        this.strategyList.map((item) => {
          item.weight = ((1 / this.strategyList.length) * 100).toFixed(2);
        });
        this.weightSubmit();
      }
    },
    addHandle(i) {
      if (i > 19) {
        this.$message({
          type: "warning",
          message: "对比产品不得多于20条",
          duration: 2000
        });
        return false;
      }
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(this.investAccount, this.investAdviser);
      });
    },
    selctInvestNameHandle(obj, tag) {
      const ok = this.strategyList.findIndex(
        (item) => item.id == obj.id && item.type == obj.type
      );
      if (ok != -1) {
        this.$message({
          type: "warning",
          message: `[${this.strategyList[ok].name}]已添加`,
          duration: 2000
        });
        return false;
      }
      this.strategyList.push({
        ...obj,
        gId: this.typeIds[obj.type - 1] + obj.id,
        weight: 0,
        leverageRatio: 1
      });

      this.beyondIncome_selList = JSON.parse(JSON.stringify(this.strategyList));
      this.one_contrastOptions_list.forEach((item) => {
        this.beyondIncome_selList.push({
          type: 7,
          id: item.id,
          gId: this.typeIds[6] + item.id,
          name: item.name
        });
      });
      // 存储当前选择的策略，避免刷新时清除掉
      localStorage.setItem(this.ss_key, JSON.stringify(this.strategyList));

      if (!tag) this.drawer = true;
    },
    // 多选策略
    selCheckctInvestNameHandle(checkList) {
      const list = checkList.filter((item) => !item.selStatus);
      const list_old = checkList.filter((item) => item.selStatus);
      let tag = false;
      this.strategyList.forEach((items, index) => {
        const i = list_old.findIndex((item) => item.id == items.gId);
        if (i == -1) {
          tag = true;
          this.strategyList.splice(index, 1);
        }
      });
      if (list.length) {
        for (let i = list.length; i > 0; i--) {
          this.selctInvestNameHandle(list[i - 1], i - 1);
        }
      } else if (tag) {
        this.drawer = true;
      }
    },
    relevanceTitleHandle(i) {
      return this.relevance_list[i].strategyName;
    },
    titleHandle(i) {
      const key_list = Object.keys(this.riskIndicators_columnLabel);
      return this.riskIndicators_columnLabel[key_list[i]];
    },
    showMonthTableClassName({ row, columnIndex }) {
      if (columnIndex === 0) {
        if (row.indexType) {
          return 'showMonthyearBorder1'
        }
        return 'showMonthyearBorder0'
      }
    },
    tableRowClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return "title-row";
      } else if (columnIndex === 1) {
        return "cell-row-0";
      } else if (columnIndex === 2) {
        return "cell-row-1";
      } else if (columnIndex === 3) {
        return "cell-row-2";
      } else if (columnIndex === 4) {
        return "cell-row-3";
      } else if (columnIndex === 5) {
        return "cell-row-4";
      } else if (columnIndex === 6) {
        return "cell-row-5";
      } else if (columnIndex === 7) {
        return "cell-row-6";
      }
      return "";
    },
    relevanceTableRowClassName({ row, rowIndex, columnIndex }) {
      const productRelevance =
        columnIndex === 0 ? "-" : row.list[columnIndex - 1].productRelevance;
      if (columnIndex === 0) {
        return "";
      } else if (productRelevance === "-") {
        return "cell-row-default";
      } else if (+productRelevance >= 0.8) {
        return "cell-row-high";
      } else if (+productRelevance < 0) {
        return "cell-row-negative";
      } else if (+productRelevance <= 0.3 && +productRelevance >= 0) {
        return "cell-row-low";
      } else {
        return "cell-row-default";
      }
    },
    // 收益风险指标
    getriskIndicators(startTime, endTime) {
      this.listLoading_riskIndicators1 = true;
      getCompareStrategyInfo({ uuid: this.uuid }).then((res) => {
        console.log("风险指标", res);
        this.listLoading_riskIndicators1 = false;

        this.list_riskIndicators = res.body.map((item) => {
          return {
            id: item.childrenId,
            type: item.childrenStatus,
            name: item.childrenName,
            ...item
          };
        });
        this.list_riskIndicators.unshift({
          id: -1,
          type: 0,
          name: "模拟组合",
          weight: 100
        });
        this.getIndexRiskByIndexTypeAndTime(startTime, endTime);
      });
    },
    // 收益风险指标 指数
    getIndexRiskByIndexTypeAndTime(startTime, endTime) {
      this.listLoading_riskIndicators2 = true;
      getIndexRiskByIndexTypeAndTime({
        indexType: this.index,
        startTime,
        endTime
      }).then((res) => {
        console.log("收益风险指标 对比", res);
        this.listLoading_riskIndicators2 = false;
        this.list_riskIndicators = this.list_riskIndicators.slice(
          0,
          this.strategyList.length + 1
        );
        Object.keys(res.body).forEach((index) => {
          const name = this.contrastOptions_obj[index];
          this.list_riskIndicators.push({
            name,
            type: 0,
            ...res.body[index]
          });
        });
      });
    },
    // 历史月度表现
    getMonthNetWorth() {
      getCompareMonthly({
        uuid: this.uuid,
        userId: this.userId
      }).then((res) => {
        const list = Object.keys(res.body)
          .map((i) => {
            return res.body[i]
          })
          .reverse()
        const new_list = []
        list.forEach((items, index) => {
          new_list[index] = {}
          items.map((el, j) => {
            new_list[index][el.month + '_growthRate'] = Number(
              el.monthIncrease,
            )
          })
          new_list[index].name = '模拟组合'
          new_list[index].year = items[0].year
          new_list[index].hasChildren = true
          new_list[index].hasClassify = true
          new_list[index].rowKey = index * 2 + 1
        })
        this.list_showMonth = new_list
        console.log('月度收益table', this.list_showMonth)
      });
    },
    // 指数月度表现
    monthContrastHandle(indexType) {
      if (indexType) {
        getMonthlyIndex({
          indexType,
          startTime: this.chart_date[0],
          endTime: this.chart_date[1]
        }).then((res) => {
          console.log("指数月度表现", res);
          const list = Object.keys(res.body)
            .map((i) => {
              return res.body[i]
            })
            .reverse()
          const indexTypeRow = this.one_contrastOptions_list.filter((item) => {
            return item.id === indexType
          })[0]
          const new_list = []
          list.forEach((items, index) => {
            new_list[index] = {}
            items.map((el, j) => {
              const month = el.month || +el.indexTime.split('-')[1]
              new_list[index][month + '_growthRate'] = Number(
                el.indexGrowthRate,
              )
            })
            new_list[index].name = `[指数] ${indexTypeRow.name}`
            new_list[index].year = items[0].year
            new_list[index].hasChildren = false
            new_list[index].hasClassify = false
            new_list[index].rowKey = `[指数]${indexTypeRow.name}_${index}`
            new_list[index].indexType = indexType
          })
          const new_list_showMonth = []
          for (let i = 0; i < this.list_showMonth.length; i++) {
            new_list_showMonth.push(this.list_showMonth[i])
            if (new_list[i]) {
              new_list_showMonth.push(new_list[i])
            }
          }
          this.list_showMonth = new_list_showMonth
        });
      } else {
        this.month_contrast = undefined;
        this.list_showMonth = []; // 月度表现列表数据
        this.list_showMonth_profit = []; // 收益分布列表数据
        this.getMonthNetWorth(this.uuid);
        this.findNetWorthExtendByStrategyId2(this.uuid);
      }
    },
    headTail(list) {
      list.unshift(list[list.length - 1]);
      list.splice(list.length - 1, 1);
    },
    segmentMaxBackHandle(list) {
      let res = []
      res = list.map((item, i) => {
        return {
          rowKey: i * 2 + 1,
          ...item,
          children: [
            {
              rowKey: i * 2 + 2,
              list: (() => {
                let res = []
                res = item.list.map((el) => {
                  return {
                    quarterName: el.quarterName,
                    sumPnl: el.maxDown,
                  }
                })
                return res
              })(),
              definition: '· 最大回撤',
            },
          ],
        }
      })
      return res
    },
    // 月度收益 tree 组合
    async loadChildTable(row, treeNode, resolve) {
      let res = null
      res = await compareMonthlyIncreaseDialog({ year: row.year, uuid: this.uuid, })
      const new_list = []
      for (const key in res.body) {
        if (Object.hasOwnProperty.call(res.body, key)) {
          const new_obj = {}
          if (res.body[key]) {
            res.body[key].forEach((item, index) => {
              new_obj[item.month + '_growthRate'] = Number(item.monthIncrease)
            })
          }
          new_obj.name = `[组合] ${key}`
          new_obj.rowKey = `${key}_${row.year}`
          new_list.push(new_obj)
        }
      }
      console.log(row.year + '月度收益table', new_list)
      resolve(new_list)
    },
    // 收益分布 列表
    findNetWorthExtendByStrategyId2() {
      this.findNetWorthExtendByStrategyId2_loading = true;
      findClassifyNetWorthExtendBySegment({
        uuid: this.uuid,
        userId: this.userId
      }).then((res) => {
        console.log("收益分布 列表", res);
        this.findNetWorthExtendByStrategyId2_loading = false;
        this.headTail(res.body);
        this.list_showMonth_profit = res.body;
        // this.findTimeScopeGrowth(this.month_contrast)
      });
    },
    // 收益分布 列表 指数
    findTimeScopeGrowth(indexType) {
      findTimeScopeGrowth({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1]
      }).then((res) => {
        console.log("对比指数 收益分布 列表", res);
        this.headTail(res.body);
        this.list_showMonth_profit.forEach((item, i) => {
          item.growth = res.body[i].growth;
        });
        this.list_showMonth_key++;
      });
    },
    // 月度回报
    getMonthNetWorthDistributed() {
      getCompareMonthlyDsitribute({
        uuid: this.uuid,
        userId: this.userId
      }).then((res) => {
        console.log("月度回报", res);
        this.list_monthNetWorthDistributed = res.body;
      });
    },
    getQuarterClassifyNetWorthDistribute() {
      this.list_monthNetWorthDistributed_loading = true;
      getCompareQuarterDistribute({
        uuid: this.uuid,
        indexType: this.month_contrast
      }).then((res) => {
        console.log("季度收益", res);
        this.list_monthNetWorthDistributed_loading = false;
        this.list_monthNetWorthDistributed = res.body;
      });
    },
    getCompareYearDistribute() {
      this.list_monthNetWorthDistributed_loading = true;
      getCompareYearDistribute({
        uuid: this.uuid,
        indexType: this.month_contrast
      }).then((res) => {
        console.log("年度收益", res);
        this.list_monthNetWorthDistributed_loading = false;
        this.list_monthNetWorthDistributed = res.body;
      });
    },
    getSegmentClassifyNetWorthDistribute() {
      this.list_monthNetWorthDistributed_loading = true;
      findSegmentCompareNetWorthDistribute({
        uuid: this.uuid,
        indexType: this.month_contrast
      }).then((res) => {
        console.log("区间收益", res);
        this.list_monthNetWorthDistributed_loading = false;
        this.list_monthNetWorthDistributed = res.body;
      });
    },
    getProductRelevance() {
      this.listLoading_productRelevance = true;
      const typeList = [0, 0, 2, 1, 4, 5, 6];
      const list = this.strategyList.map((item) => {
        return {
          ...item,
          type: typeList[item.type]
        };
      });
      getProductRelevanceNew({ list }).then((res) => {
        this.listLoading_productRelevance = false;
        this.relevance_list = res.body.list;
        if (this.relevance_list.length) {
          this.highRelevanceRate =
            res.body.relevanceProportionVo.highRelevanceRate;
          this.lowRelevanceRate =
            res.body.relevanceProportionVo.lowRelevanceRate;
          this.negativeRelevanceRate =
            res.body.relevanceProportionVo.negativeRelevanceRate;
        }
        // console.log("产品相关性 - ", res.body);
      });
    },
    refresh() {
      location.reload();
    },
    /**
     * 表格数据单行显示内边距为0
     */
    cellClass(row) {
      if (
        (!row.column.label ||
          row.column.label === "名称") &&
        this.maxNameWidth < 400
      ) {
        return "cell-pad-0 nowrap";
      } else if (this.maxNameWidth >= 400) {
        return "cell-pad-0 clamp2Ellipsis";
      }
      return "";
    },
    /**
     * table column 自适应列宽
     * @param label 表名
     * @param prop 表格数据
     * @param tableData 表格数据
     */
    flexColumnWidth(label, prop, tableData) {
      const arr = tableData.map((x) => x[prop]);
      arr.push(label);
      if (getMaxLength(arr) + 80 >= 400) {
        this.maxNameWidth = 400
      }else {
        this.maxNameWidth = getMaxLength(arr) + 80
      }
      return this.maxNameWidth
    },
  }
  // beforeupdate
};
</script>
<style lang="scss">
</style>
<style lang="scss" scoped>
.mlOverflow{
  max-height: 30px;
  &::after{
  content: "...";
    display: block;
    position: absolute;
    bottom: 2px;
    right: 12px;
    font-size: 18px;
    padding-left: 10px;
    padding-bottom: 4px;
    background: linear-gradient(to right, rgba(255, 255, 255, 0.8), #ffffff);
  }
}
.el-table--striped .el-table__body tr.el-table__row--striped td{
  .mlOverflow::after{
    background: linear-gradient(to right, rgba(241, 245, 248, 0.8), rgba(241, 245, 248, 1));
  }
}
.contrast-page {
 .relevance-tip {
      line-height: 12px;
      display: flex;
      align-items: center;
      color: #666;
      font-size: 12px;
      margin-top: 10px;
      .yellow-block {
        width: 12px;
        height: 12px;
        background: #FFE68C;
        margin: 0 3px;
      }
      .red-block {
        width: 12px;
        height: 12px;
        background: #FCC6BA;
        margin: 0 3px 0 8px;
      }
      .blue-block {
        width: 12px;
        height: 12px;
        background: #69c0ff;
        margin: 0 3px 0 8px;
      }
      .green-block {
        width: 12px;
        height: 12px;
        background: #DAEED5;
        margin: 0 3px 0 8px;
      }
      .gray-block {
        width: 12px;
        height: 12px;
        background: #f5f5f5;
        margin: 0 3px 0 8px;
      }

    }
.afterInvestDel-page {
    .title {
      font-size: 26px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #262626;
    }

  }
  .head {
    display: flex;
    flex-wrap: wrap;
    .card {
      width: 23.5%;
      height: 40px;
      padding: 0 15px;
      background: #ecf1f6;
      border-radius: 2px;
      margin-left: 2%;
      &:nth-child(4n + 1) {
        margin-left: 0;
      }
      &:hover {
        color: #1890ff;
      }
      &:nth-child(n + 4) {
        margin-top: 4px;
      }
      .close {
        font-size: 18px;
        cursor: pointer;
      }
    }
    .add {
      background: #fff;
      border: 1px dashed #999;
    }
  }
  .nav {
    height: 56px;
    margin-top: 20px;
    padding: 0 24px;
    background: #ffffff;
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    .nav-left {
      font-size: 18px;
      font-weight: 400;
      color: #262626;
      .nav-item {
        font-family: PingFangSC-Regular, PingFang SC;
        cursor: pointer;
        line-height: 56px;
        & + .nav-item {
          margin-left: 48px;
        }
      }
    }
    .navActive {
      color: #1890ff;
      border-bottom: 2px solid #1890ff;
    }
  }
  .column {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    margin-top: 30px;
    cursor: pointer;
    user-select: none;
    .el-icon {
      color: #4f95dd;
      font-weight: bold;
      margin-left: 6px;
    }
    .openChunk {
      transform: rotate(90deg);
    }
    &::before {
      display: inline-block;
      content: "";
      width: 6px;
      height: 26px;
      background: #42b983;
      margin-right: 6px;
    }
  }
  ::v-deep .el-table {
    .title-row {
      background: #dcedff !important;
    }
    .cell-row-0 {
      background: #fff7f7 !important;
    }
    .cell-row-1 {
      background: #fffcf5 !important;
    }
    .cell-row-2 {
      background: #fffbfd !important;
    }
    .cell-row-3 {
      background: #fafffb !important;
    }
    .cell-row-4 {
      background: #fffcfc !important;
    }
    .cell-row-5 {
      background: #f9fdff !important;
    }
    .cell-row-6 {
      background: #fdfbfe !important;
    }

    // 历史月度表现
    .showMonthyearBorder0 {
      border-right: 2px solid #e16757;
    }
    .showMonthyearBorder1 {
      border-right: 2px solid #78b2eb;
    }
  }
  .line {
    display: flex;
    .showMonth {
      display: flex;
      align-items: center;
      & + .showMonth {
        margin-left: 15px;
      }
      .round {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        margin-right: 5px;
      }
      .round1 {
        background: #e16757;
      }
      .round2 {
        background: #78b2eb;
      }
    }
  }
  .icon-chartpie {
    font-size: 12px;
  }
  .drawerContent {
    height: calc(100vh - 124px);
  }
  .pubChunk_footer {
    padding: 0 24px;
  }

  .drawerBtn_active {
    color: #1890ff;
    border-color: #badeff;
    background-color: #e8f4ff;
  }
}

.app-container1 {
  min-height: 100vh;
  background: #f0f2f5;
}
</style>
